<template>
    <div class="storage-add-container">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <div class="header-content">
                <div class="title-section">
                    <div class="icon-wrapper">
                        <el-icon class="page-icon">
                            <House />
                        </el-icon>
                    </div>
                    <div class="title-text">
                        <h1>新增仓库</h1>
                        <p>创建新的仓库信息，完善仓库管理</p>
                    </div>
                </div>
                <el-button @click="goBack" type="info" plain class="back-btn">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                    返回列表
                </el-button>
            </div>
        </div>

        <!-- 表单区域 -->
        <div class="form-section">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="formRules" label-width="140px" class="storage-form">
                <!-- 基本信息卡片 -->
                <div class="form-card">
                    <div class="card-header">
                        <el-icon class="card-icon">
                            <Document />
                        </el-icon>
                        <h3>基本信息</h3>
                    </div>

                    <!-- 第一行：仓库编号和仓库名称 -->
                    <div class="form-row">
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="仓库编号" prop="storageCode">
                                    <el-input v-model="ruleForm.storageCode" readonly placeholder="自动生成"
                                        class="code-input">
                                        <template #append>
                                            <el-button @click="generateStorageCodeHandler" :loading="generating"
                                                type="primary" class="generate-btn">
                                                <el-icon>
                                                    <Refresh />
                                                </el-icon>
                                                重新生成
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="仓库名称" prop="storageName">
                                    <el-input v-model="ruleForm.storageName" placeholder="请输入仓库名称" clearable
                                        class="name-input" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>

                    <!-- 第二行：仓库容量和库位数量 -->
                    <div class="form-row">
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="仓库容量" prop="storageCapacity">
                                    <el-input-number v-model="ruleForm.storageCapacity" :min="1" :max="999999"
                                        placeholder="请输入仓库容量" class="capacity-input">
                                        <template #suffix>m³</template>
                                    </el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="库位数量" prop="locationNumder">
                                    <el-input-number v-model="ruleForm.locationNumder" :min="1" :max="9999"
                                        placeholder="请输入库位数量" class="location-input" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <!-- 管理信息卡片 -->
                <div class="form-card">
                    <div class="card-header">
                        <el-icon class="card-icon">
                            <User />
                        </el-icon>
                        <h3>管理信息</h3>
                    </div>

                    <!-- 第三行：所属部门和仓库主管 -->
                    <div class="form-row">
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <el-form-item label="所属部门" prop="department_Id">
                                    <el-select v-model="ruleForm.department_Id" placeholder="请选择所属部门" clearable
                                        class="department-select">
                                        <el-option v-for="dept in departmentOptions" :key="dept.department_Id"
                                            :label="dept.department_Name" :value="dept.department_Id" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="仓库主管" prop="user_WorkCode">
                                    <el-select v-model="ruleForm.user_WorkCode" placeholder="请选择仓库主管" clearable
                                        class="manager-select">
                                        <el-option v-for="user in userOptions" :key="user.user_WorkCode"
                                            :label="user.user_Name" :value="user.user_WorkCode" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <!-- 详细信息卡片 -->
                <div class="form-card">
                    <div class="card-header">
                        <el-icon class="card-icon">
                            <Location />
                        </el-icon>
                        <h3>详细信息</h3>
                    </div>

                    <!-- 第四行：仓库地址 -->
                    <div class="form-row">
                        <el-form-item label="仓库地址" prop="storageAdder">
                            <el-input v-model="ruleForm.storageAdder" type="textarea" :rows="3" placeholder="请输入仓库详细地址"
                                clearable class="address-input" />
                        </el-form-item>
                    </div>

                    <!-- 第五行：仓库状态 -->
                    <div class="form-row">
                        <el-form-item label="仓库状态" prop="storageState">
                            <el-radio-group v-model="ruleForm.storageState" class="status-radio">
                                <el-radio :label="true" class="status-option">
                                    <el-icon class="status-icon">
                                        <CircleCheck />
                                    </el-icon>
                                    启用
                                </el-radio>
                                <el-radio :label="false" class="status-option">
                                    <el-icon class="status-icon">
                                        <CircleClose />
                                    </el-icon>
                                    停用
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>

                    <!-- 第六行：备注 -->
                    <div class="form-row">
                        <el-form-item label="备注信息">
                            <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="请输入备注信息（可选）"
                                clearable class="remark-input" />
                        </el-form-item>
                    </div>
                </div>
                <!-- 库位信息卡片 -->
                <div class="form-card">
                    <div class="card-header">
                        <el-icon class="card-icon">
                            <Location />
                        </el-icon>
                        <h3>库位信息</h3>
                    </div>
                </div>
                <div>
                    <div class="table-actions">
                        <el-button type="primary" @click="openAddLocationDialog" class="add-btn">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            新增库位
                        </el-button>
                        <el-button 
                            type="danger" 
                            @click="batchDeleteLocations" 
                            :disabled="selectedLocations.length === 0"
                            class="batch-delete-btn"
                        >
                            <el-icon>
                                <Delete />
                            </el-icon>
                            批量删除 ({{ selectedLocations.length }})
                        </el-button>
                    </div>
                    <el-table :data="tableData" style="width: 100%" @selection-change="handleLocationSelectionChange">
                        <el-table-column type="selection" :selectable="selectable" width="55" />
                        <el-table-column fixed prop="locationCode" label="编号" width="150" />
                        <el-table-column prop="locationName" label="库位名称" width="120" />
                        <el-table-column prop="lTypeName" label="库位类型" width="120" />
                        <el-table-column fixed="right" label="Operations" min-width="120">
                            <template #default="scoped">
                                <el-button link type="primary" size="small" @click="handleClick(scoped.row.locationId)">
                                    删除
                                </el-button>
                                <el-button link type="primary" size="small"
                                    @click="handleUpdate(scoped.row)">修改</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                    <!-- 添加库位 -->
                    <el-dialog v-model="dialogTableVisible" title="新增库位" width="800">
                        <el-form ref="ruleFormRefs" style="max-width: 600px" :model="ruleForms" label-width="auto">
                            <div class="form-row">
                                <el-form-item label="库位编号" prop="locationCode">
                                    <el-input v-model="ruleForms.locationCode" readonly placeholder="自动生成"
                                        class="code-input">
                                        <template #append>
                                            <el-button @click="getLocationCode" :loading="generatingLocation"
                                                type="primary" class="generate-btn">
                                                <el-icon>
                                                    <Refresh />
                                                </el-icon>
                                                重新生成
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="库位名称" prop="locationName">
                                    <el-input v-model="ruleForms.locationName" />
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="库位类型" prop="lTypeId">
                                    <el-select v-model="ruleForms.lTypeId" placeholder="请选择库位类型">
                                        <el-option v-for="a in LType" :key="a.lTypeId" :label="a.lTypeName"
                                            :value="a.lTypeId" />
                                    </el-select>
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="仓库" prop="depotId">
                                    <el-select v-model="ruleForms.depotId" placeholder="请选择仓库">
                                        <el-option v-for="a in Depot" :key="a.depotId" :label="a.depotName"
                                            :value="a.depotId" />
                                    </el-select>
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="是否禁用" prop="isState">
                                    <!-- <el-input v-model="ruleForms.isState" /> -->
                                    <el-radio-group v-model="ruleForms.isState">
                                        <el-radio :label="true" size="true">启用</el-radio>
                                        <el-radio :label="false" size="false">禁用</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="是否默认" prop="isPreset">
                                    <!-- <el-input v-model="ruleForms.isPreset" /> -->
                                    <el-radio-group v-model="ruleForms.isPreset">
                                        <el-radio :label="true" size="true">是</el-radio>
                                        <el-radio :label="false" size="false">否</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item label="备注" prop="locationRemark">
                                    <el-input v-model="ruleForms.locationRemark" />
                                </el-form-item>
                            </div>

                            <div class="form-row">
                                <el-form-item>
                                    <el-button type="primary" @click="submitForms(ruleFormRefs)">
                                        添加库位
                                    </el-button>
                                    <el-button @click="resetForm1(ruleFormRefs)">取消库位</el-button>
                                </el-form-item>
                            </div>

                        </el-form>
                    </el-dialog>
                    <!-- 修改库位 -->
                    <div>
                        <el-dialog v-model="dialogTableVisible1" title="修改库位" width="800">
                            <el-form ref="ruleFormRefs" style="max-width: 600px" :model="ruleForms" label-width="auto">
                                <div class="form-row">
                                    <el-form-item label="库位编号" prop="locationCode">
                                        <el-input v-model="ruleForms.locationCode" readonly placeholder="自动生成"
                                            class="code-input">
                                            <template #append>
                                                <el-button @click="getLocationCode" :loading="generatingLocation"
                                                    type="primary" class="generate-btn">
                                                    <el-icon>
                                                        <Refresh />
                                                    </el-icon>
                                                    重新生成
                                                </el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="库位名称" prop="locationName">
                                        <el-input v-model="ruleForms.locationName" />
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="库位类型" prop="lTypeId">
                                        <el-select v-model="ruleForms.lTypeId" placeholder="请选择库位类型">
                                            <el-option v-for="a in LType" :key="a.lTypeId" :label="a.lTypeName"
                                                :value="a.lTypeId" />
                                        </el-select>
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="仓库" prop="depotId">
                                        <el-select v-model="ruleForms.depotId" placeholder="请选择仓库">
                                            <el-option v-for="a in Depot" :key="a.depotId" :label="a.depotName"
                                                :value="a.depotId" />
                                        </el-select>
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="是否禁用" prop="isState">
                                        <!-- <el-input v-model="ruleForms.isState" /> -->
                                        <el-radio-group v-model="ruleForms.isState">
                                            <el-radio :label="true" size="true">启用</el-radio>
                                            <el-radio :label="false" size="false">禁用</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="是否默认" prop="isPreset">
                                        <!-- <el-input v-model="ruleForms.isPreset" /> -->
                                        <el-radio-group v-model="ruleForms.isPreset">
                                            <el-radio :label="true" size="true">是</el-radio>
                                            <el-radio :label="false" size="false">否</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item label="备注" prop="locationRemark">
                                        <el-input v-model="ruleForms.locationRemark" />
                                    </el-form-item>
                                </div>

                                <div class="form-row">
                                    <el-form-item>
                                        <el-button type="primary" @click="submitForms1()">
                                            修改库位
                                        </el-button>
                                        <!-- <el-button @click="resetForm1()">取消库位</el-button> -->
                                    </el-form-item>
                                </div>

                            </el-form>
                        </el-dialog>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="form-actions">
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="submitting"
                            class="submit-btn">
                            <el-icon>
                                <Check />
                            </el-icon>
                            保存仓库
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)" class="reset-btn">
                            <el-icon>
                                <RefreshLeft />
                            </el-icon>
                            重置表单
                        </el-button>
                        <el-button @click="goBack" class="cancel-btn">
                            <el-icon>
                                <Close />
                            </el-icon>
                            取消操作
                        </el-button>
                    </el-form-item>
                </div>
            </el-form>

        </div>


    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft, Check, RefreshLeft, Close, Refresh, House, Document, User, Location, CircleCheck, CircleClose, Plus, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

import { generateStorageCode, fetchExistingStorageCodes } from '@/utils/codeGenerator'
import { http } from '@/axios/axiosHelpers'

const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const submitting = ref(false)
const generating = ref(false)
const generatingLocation = ref(false)

// 表单数据
const ruleForm = reactive({
    storageCode: "",
    storageName: "",
    storageCapacity: 500,
    storageAdder: "",
    department_Id: null as number | null,
    user_WorkCode: "",
    locationNumder: 10,
    storageState: true,
    description: '',
    loginUserName: localStorage.getItem("userName")
})

// 表单验证规则
const formRules: FormRules = {
    storageCode: [
        { required: true, message: '仓库编号已自动生成', trigger: 'blur' }
    ],
    storageName: [
        { required: true, message: '请输入仓库名称', trigger: 'blur' },
        { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    storageCapacity: [
        { required: true, message: '请输入仓库容量', trigger: 'blur' },
        { type: 'number', min: 1, message: '仓库容量必须大于0', trigger: 'blur' }
    ],
    locationNumder: [
        { required: true, message: '请输入库位数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '库位数量必须大于0', trigger: 'blur' }
    ],
    department_Id: [
        { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    user_WorkCode: [
        { required: true, message: '请选择仓库主管', trigger: 'change' }
    ],
    storageAdder: [
        { required: true, message: '请输入仓库地址', trigger: 'blur' },
        { min: 5, max: 200, message: '仓库地址长度在 5 到 200 个字符', trigger: 'blur' }
    ]
}

onMounted(() => {
    getDepartment();
    getuserOptions();
    getData();
    getDepot();
    getLType();
})

// 部门选项
const departmentOptions = ref([{
    "department_Id": '',
    "department_Name": "",
}])
const getDepartment = () => {
    http.get("/basicread/api/DepartMentAll/ShowDepartMent").then(res => {
        departmentOptions.value = res.data.data
    })
}
  
// 用户选项
const userOptions = ref([{
    "user_WorkCode": "",
    "user_Name": "",
}])
const getuserOptions = () => {
    http.get("/basicread/api/UserValues/ShowUser?PageIndex=1&PageSize=15").then(res => {
        userOptions.value = res.data.data.data
    })
}
//仓库
const Depot = ref([{
    "depotId": '',
    "depotName": "",
}])
const getDepot = () => {
    console.log(Depot.value);
    http.get("/basicread/api/Depot/GetDepot").then(res => {
        Depot.value = res.data.data
    })
}
//库位类型
const LType = ref([{
    "lTypeId": '',
    "lTypeName": "",
}])
const getLType = () => {
    console.log(Depot.value);
    http.get("/basicread/api/Location/GetLocationType").then(res => {
        LType.value = res.data.data
    })
}

// 已存在的仓库编号列表（用于检查重复）
const existingCodes = ref<string[]>([])

// 生成仓库编号
const generateStorageCodeHandler = async () => {
    generating.value = true
    try {
        const newCode = await generateStorageCode(existingCodes.value)
        ruleForm.storageCode = newCode
        ElMessage.success('仓库编号生成成功')
    } catch (error) {
        console.error('生成仓库编号失败:', error)
        ElMessage.error('生成仓库编号失败')
    } finally {
        generating.value = false
    }
}

// 获取已存在的仓库编号列表
const fetchExistingCodes = async () => {
    try {
        existingCodes.value = await fetchExistingStorageCodes()
    } catch (error) {
        console.error('获取已存在编号失败:', error)
        // 如果获取失败，使用一些示例编号作为备用
        existingCodes.value = ['CKBH1358', 'CKBH8607', 'CKBH1234', 'CKBH5678']
    }
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    try {
        await formEl.validate((valid, fields) => {
            if (valid) {
                submitting.value = true
                http.post("/basicwrite/api/Storage/AddStorage", ruleForm).then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.msg)
                        goBack()
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                }).catch(error => {
                    console.error('提交失败:', error)
                    ElMessage.error('提交失败，请检查网络连接')
                }).finally(() => {
                    submitting.value = false
                })
            } else {
                console.log('error submit!', fields)
                ElMessage.warning('请完善表单信息')
            }
        })
    } catch (error) {
        submitting.value = false
        console.error('提交表单失败:', error)
        ElMessage.error('提交表单失败')
    }
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return

    ElMessageBox.confirm('确定要重置表单吗？所有已填写的信息将被清空。', '确认重置', {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        formEl.resetFields()

        // 重置后重新生成仓库编号
        Object.assign(ruleForm, {
            storageCode: "",
            storageName: "",
            storageCapacity: 500,
            storageAdder: "",
            department_Id: null,
            user_WorkCode: "",
            locationNumder: 10,
            storageState: true,
            description: '',
            loginUserName: localStorage.getItem("userName")
        })

        // 重新生成仓库编号
        generateStorageCodeHandler()
        ElMessage.success('表单已重置')
    }).catch(() => {
        // 用户取消重置
    })
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}

// 组件挂载时初始化
onMounted(async () => {
    // 获取已存在的仓库编号
    await fetchExistingCodes()

    // 生成初始仓库编号
    await generateStorageCodeHandler()
})


//库位
const selectable = (row: any) => ![1, 2].includes(row.id)

// 选中的库位
const selectedLocations = ref<any[]>([])

// 处理库位多选
const handleLocationSelectionChange = (selection: any[]) => {
    selectedLocations.value = selection
    console.log('选中的库位:', selectedLocations.value)
    console.log('选中的库位ID:', selectedLocations.value.map(item => item.locationId))
}

const dialogTableVisible = ref(false)
const dialogTableVisible1 = ref(false)

const ruleFormRefs = ref<FormInstance>()
const ruleForms = reactive({
    "locationId": '',
    "locationCode": "",
    "locationName": "",
    "lTypeId": '',
    "depotId": '',
    "isState": true,
    "isPreset": true,
    "locationRemark": ""
})

const locationOptions = ['Home', 'Company', 'School']



const submitForms = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            http.post("/basicwrite/api/Location/AddLocation", ruleForms).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    dialogTableVisible.value = false;
                    getData();
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForms = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))


const handleClick = (locationId: any) => {
    ElMessageBox.confirm(
        '确定删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            http.get("/basicwrite/api/Location/DelLocation?LocationId=" + locationId).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    getData();
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除被取消',
            })
        })
}

// 批量删除库位
const batchDeleteLocations = () => {
    if (selectedLocations.value.length === 0) {
        ElMessage.warning('请先选择要删除的库位')
        return
    }

    const locationIds = selectedLocations.value.map(item => item.locationId)
    const locationNames = selectedLocations.value.map(item => item.locationName).join('、')

    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedLocations.value.length} 个库位吗？\n库位名称：${locationNames}`,
        '批量删除警告',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 逐个删除选中的库位
                const deletePromises = locationIds.map(locationId => 
                    http.get(`/basicwrite/api/Location/DelLocation?LocationId=${locationId}`)
                )
                
                const results = await Promise.all(deletePromises)
                const successCount = results.filter(res => res.data.code === 200).length
                const failCount = results.length - successCount

                if (failCount === 0) {
                    ElMessage.success(`成功删除 ${successCount} 个库位`)
                } else {
                    ElMessage.warning(`删除完成：成功 ${successCount} 个，失败 ${failCount} 个`)
                }

                // 清空选中状态并刷新数据
                selectedLocations.value = []
                getData()
            } catch (error) {
                console.error('批量删除失败:', error)
                ElMessage.error('批量删除失败，请重试')
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '批量删除被取消',
            })
        })
}

const tableData = ref([]);
const getData = () => {
    http.get("/basicread/api/Location/GetLocation").then(res => {
        tableData.value = res.data.data
    })
}
// 重置表单
const resetForm1 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    ElMessageBox.confirm('确定要重置表单吗？所有已填写的信息将被清空。', '确认重置', {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        formEl.resetFields()

        // 重置后重新生成库位编号
        Object.assign(ruleForms, {
            "locationCode": "",
            "locationName": "",
            "lTypeId": '',
            "depotId": '',
            "isState": true,
            "isPreset": true,
            "locationRemark": ""
        })

        // 自动生成新的库位编号
        await getLocationCode()

        ElMessage.success('表单已重置，库位编号已重新生成')
    }).catch(() => {
        // 用户取消重置
    })
}
//自动生成库位编号
const getLocationCode = async () => {
    generatingLocation.value = true
    try {
        // 获取现有的库位编号列表
        const response = await axios.get("http://localhost:5011/api/Location/GetLocation")
        const existingLocations = response.data.data || []

        // 提取所有库位编号
        const existingCodes = existingLocations.map((location: any) => location.locationCode).filter(Boolean)

        // 生成新的库位编号
        let newCode = ''

        // 查找最大的编号
        const maxCode = existingCodes.reduce((max: string, current: string) => {
            const currentNum = parseInt(current.replace(/\D/g, '')) || 0
            const maxNum = parseInt(max.replace(/\D/g, '')) || 0
            return currentNum > maxNum ? current : max
        }, 'KW001')

        // 从最大编号中提取数字部分
        const maxNumber = parseInt(maxCode.replace(/\D/g, '')) || 0
        let nextNumber = maxNumber + 1

        // 生成新编号，格式：KW + 4位数字
        newCode = `KW${nextNumber.toString().padStart(4, '0')}`

        // 确保编号唯一
        while (existingCodes.includes(newCode)) {
            nextNumber++
            newCode = `KW${nextNumber.toString().padStart(4, '0')}`
        }

        // 更新表单中的库位编号
        ruleForms.locationCode = newCode

        ElMessage.success('库位编号生成成功')
        return newCode
    } catch (error) {
        console.error('生成库位编号失败:', error)
        ElMessage.error('生成库位编号失败')
        // 如果获取失败，使用时间戳生成编号
        const timestamp = Date.now().toString().slice(-6)
        const fallbackCode = `KW${timestamp}`
        ruleForms.locationCode = fallbackCode
        return fallbackCode
    } finally {
        generatingLocation.value = false
    }
}

// 打开新增库位对话框
const openAddLocationDialog = async () => {
    try {
        // 重置库位表单
        Object.assign(ruleForms, {
            "locationCode": "",
            "locationName": "",
            "lTypeId": '',
            "depotId": '',
            "isState": true,
            "isPreset": true,
            "locationRemark": ""
        })

        // 自动生成库位编号
        await getLocationCode()

        // 打开对话框
        dialogTableVisible.value = true

        ElMessage.success('库位编号已自动生成')
    } catch (error) {
        console.error('打开对话框失败:', error)
        ElMessage.error('打开对话框失败')
    }
}

//修改库位
const handleUpdate = (row: any) => {
    dialogTableVisible1.value = true;
    Object.assign(ruleForms, row);
}
const submitForms1=()=>{
    http.post("/basicwrite/api/Location/UpdateLocation",ruleForms).then(res=>{
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg)
        dialogTableVisible1.value=false
        getData();
    }
    else
    {
        ElMessage.error(res.data.msg);
    }
    })
}
</script>

<style scoped>
.storage-add-container {
    padding: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    position: relative;
}

.storage-add-container::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
    pointer-events: none;
}

.page-header {
    padding: 40px 60px 30px;
    position: relative;
    z-index: 1;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 1200px;
    margin: 0 auto;
}

.title-section {
    display: flex;
    align-items: center;
    gap: 20px;
}

.icon-wrapper {
    width: 60px;
    height: 60px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.page-icon {
    font-size: 28px;
    color: white;
}

.title-text h1 {
    margin: 0 0 8px 0;
    color: white;
    font-size: 32px;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title-text p {
    margin: 0;
    color: rgba(255, 255, 255, 0.9);
    font-size: 16px;
    font-weight: 400;
}

.back-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
}

.back-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.form-section {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 60px 60px;
    position: relative;
    z-index: 1;
}

.storage-form {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.form-card {
    margin-bottom: 30px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid #f0f2f5;
    overflow: hidden;
}

.form-card:last-of-type {
    margin-bottom: 0;
}

.card-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 24px 30px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 1px solid #e2e8f0;
}

.card-icon {
    font-size: 20px;
    color: #3b82f6;
}

.card-header h3 {
    margin: 0;
    color: #1e293b;
    font-size: 18px;
    font-weight: 600;
}

.form-row {
    padding: 30px;
    border-bottom: 1px solid #f1f5f9;
}

.form-row:last-child {
    border-bottom: none;
}

.form-actions {
    padding: 40px 30px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-top: 1px solid #e2e8f0;
    text-align: center;
}

/* 表单控件样式 */
:deep(.el-form-item__label) {
    font-weight: 600;
    color: #374151;
    font-size: 14px;
}

:deep(.el-form-item) {
    margin-bottom: 0;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

:deep(.el-input__wrapper:hover) {
    border-color: #3b82f6;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
    border-radius: 8px;
}

:deep(.el-select) {
    width: 100%;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
}

:deep(.el-textarea__inner) {
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;
    resize: vertical;
}

:deep(.el-textarea__inner:hover) {
    border-color: #3b82f6;
}

:deep(.el-textarea__inner:focus) {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 特殊输入框样式 */
.code-input :deep(.el-input__wrapper) {
    background: #f8fafc;
    border-color: #d1d5db;
}

.generate-btn {
    border-radius: 0 8px 8px 0;
    height: 100%;
    padding: 0 16px;
    font-size: 12px;
}

.status-radio {
    display: flex;
    gap: 40px;
}

.status-option {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    transition: all 0.3s ease;
    cursor: pointer;
}

.status-option:hover {
    border-color: #3b82f6;
    background: #f0f9ff;
}

.status-option.is-checked {
    border-color: #3b82f6;
    background: #eff6ff;
    color: #1d4ed8;
}

.status-icon {
    font-size: 16px;
}

/* 按钮样式 */
.submit-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    padding: 14px 32px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
    transition: all 0.3s ease;
}

.submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

.reset-btn {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    border: none;
    color: white;
    padding: 14px 32px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
    transition: all 0.3s ease;
}

.reset-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(245, 158, 11, 0.4);
}

.cancel-btn {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    border: none;
    color: white;
    padding: 14px 32px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(107, 114, 128, 0.3);
    transition: all 0.3s ease;
}

.cancel-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(107, 114, 128, 0.4);
}

:deep(.el-button) {
    margin-right: 16px;
    font-weight: 500;
}

:deep(.el-button:last-child) {
    margin-right: 0;
}

/* 错误状态样式 */
:deep(.el-form-item.is-error .el-input__wrapper) {
    border-color: #ef4444;
    box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

:deep(.el-form-item.is-error .el-textarea__inner) {
    border-color: #ef4444;
    box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
    color: #ef4444;
}

/* 表格操作区域样式 */
.table-actions {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
    align-items: center;
}

.batch-delete-btn {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    border: none;
    color: white;
    padding: 12px 20px;
    font-size: 14px;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
    transition: all 0.3s ease;
}

.batch-delete-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
}

.batch-delete-btn:disabled {
    background: #d1d5db;
    color: #6b7280;
    cursor: not-allowed;
    box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 1024px) {
    .page-header {
        padding: 30px 40px 20px;
    }

    .form-section {
        padding: 0 40px 40px;
    }

    .title-text h1 {
        font-size: 28px;
    }
}

@media (max-width: 768px) {
    .storage-add-container {
        padding: 0;
    }

    .page-header {
        padding: 20px 20px 15px;
    }

    .header-content {
        flex-direction: column;
        gap: 20px;
        text-align: center;
    }

    .title-section {
        flex-direction: column;
        gap: 15px;
    }

    .icon-wrapper {
        width: 50px;
        height: 50px;
    }

    .page-icon {
        font-size: 24px;
    }

    .title-text h1 {
        font-size: 24px;
    }

    .title-text p {
        font-size: 14px;
    }

    .form-section {
        padding: 0 20px 20px;
        max-width: 100%;
    }

    .storage-form {
        border-radius: 16px;
    }

    .form-card {
        border-radius: 12px;
    }

    .card-header {
        padding: 20px;
    }

    .form-row {
        padding: 20px;
    }

    .form-actions {
        padding: 30px 20px;
    }

    .status-radio {
        gap: 20px;
        flex-direction: column;
    }

    .status-option {
        width: 100%;
        justify-content: center;
    }

    .table-actions {
        flex-direction: column;
        gap: 8px;
    }

    .table-actions .el-button {
        width: 100%;
        margin-bottom: 8px;
    }

    :deep(.el-button) {
        margin-bottom: 12px;
        width: 100%;
        margin-right: 0;
    }
}

@media (max-width: 480px) {
    .page-header {
        padding: 15px 15px 10px;
    }

    .form-section {
        padding: 0 15px 15px;
    }

    .storage-form {
        border-radius: 12px;
    }

    .form-card {
        border-radius: 8px;
    }

    .card-header {
        padding: 15px;
    }

    .form-row {
        padding: 15px;
    }

    .form-actions {
        padding: 20px 15px;
    }

    .title-text h1 {
        font-size: 20px;
    }

    .title-text p {
        font-size: 12px;
    }
}
</style>
